package com.sunl.mall.common.response;

 import com.sunl.mall.common.error.CommonError;
 import lombok.EqualsAndHashCode;

import java.io.Serializable;
import java.util.Collection;

@EqualsAndHashCode
public class CommonResponse<T> implements Serializable {
    private final static long serialVersionUID = 1L;

    private T result;

    private int errorCode;

    private String errorMsg;

    private boolean success = false;

    public CommonResponse() {
    }

    public CommonResponse(T result) {
        this.setResult(result);
    }

    public CommonResponse(int errorCode, String errorMsg) {
        this.setErrorCode(errorCode);
        this.setErrorMsg(errorMsg);
    }

    public CommonResponse(T result, int errorCode, String errorMsg) {
        this.setErrorCode(errorCode);
        this.setErrorMsg(errorMsg);
        this.setResult(result);
    }

    public void setError(int errorCode, String errorMsg) {
        this.setErrorCode(errorCode);
        this.setErrorMsg(errorMsg);
    }

    public void setError(CommonError error) {
        this.setError(error.getErrorCode(), error.getErrorDesc());
    }

    public void setResult(T result) {
        if (result != null) {
            this.success = true;
            this.result = result;
        } else {
            this.success = false;
        }
    }

    public T getResult() {
        return this.result;
    }

    public int getErrorCode() {
        return this.errorCode;
    }

    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMsg() {
        return this.errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    public boolean isSuccess() {
        return this.success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String toString() {
        String resultTemp = null;
        if (this.getResult() != null) {
            if (this.getResult() instanceof Collection && ((Collection) this.getResult()).size() > 20) {
                resultTemp = this.getResult().getClass().getSimpleName() + "[...]";
            } else {
                resultTemp = this.getResult().toString();
            }
        }

        return this.toSimpleString(resultTemp);
    }

    private String toSimpleString(String resultTemp) {
        return "CommonResponse{result=" + resultTemp + ", errorCode='" + this.errorCode + '\'' + ", errorMsg='" + this.errorMsg + '\'' + ", success=" + this.success + '}';
    }
}
